package com.winhxd.b2c.customer.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.winhxd.b2c.common.constant.BusinessCode;
import com.winhxd.b2c.common.domain.PagedList;
import com.winhxd.b2c.common.domain.customer.condition.DistributorChannelCondition;
import com.winhxd.b2c.common.domain.customer.condition.DistributorChannelTypeCondition;
import com.winhxd.b2c.common.domain.customer.enums.CustomerUserLevelEnum;
import com.winhxd.b2c.common.domain.customer.model.CustomerChannel;
import com.winhxd.b2c.common.domain.customer.model.CustomerDistributorChannel;
import com.winhxd.b2c.common.domain.customer.model.CustomerDistributorLevel;
import com.winhxd.b2c.common.domain.customer.vo.CustomerDistributorChannelTypeVO;
import com.winhxd.b2c.common.domain.customer.vo.CustomerDistributorTypeAndChannelVO;
import com.winhxd.b2c.common.exception.BusinessException;
import com.winhxd.b2c.common.util.JsonUtil;
import com.winhxd.b2c.customer.dao.CustomerChannelMapper;
import com.winhxd.b2c.customer.dao.CustomerDistributorChannelMapper;
import com.winhxd.b2c.customer.service.DistributorChannelService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class DistributorChannelServiceImpl implements DistributorChannelService {

    private static final Logger logger = LoggerFactory.getLogger(DistributorChannelServiceImpl.class);
    @Autowired
    private CustomerChannelMapper customerChannelMapper;

    @Autowired
    private CustomerDistributorChannelMapper customerDistributorChannelMapper;

    /**
     * 分销商
     *
     * @param condition
     * @return
     */
    @Override
    public PagedList<CustomerDistributorChannelTypeVO> findCustomerDistribtorChannelTypeList(DistributorChannelTypeCondition condition) {

        PagedList<CustomerDistributorChannelTypeVO> listPagedList = new PagedList<CustomerDistributorChannelTypeVO>();
        PageHelper.startPage(condition.getPageNo(), condition.getPageSize());
        List<CustomerDistributorChannelTypeVO> distribtorChannelTypeList = customerChannelMapper.findCustomerDistribtorChannelTypeList(condition);
        PageInfo pageInfo = new PageInfo(distribtorChannelTypeList);
        listPagedList.setPageNo(condition.getPageNo());
        listPagedList.setPageSize(condition.getPageSize());
        listPagedList.setData(distribtorChannelTypeList);
        listPagedList.setTotalRows(pageInfo.getTotal());
        return listPagedList;
    }

    /**
     * 更新分销商渠道类型状态
     *
     * @param condition
     * @return
     */
    @Override
    public Boolean modifyDistriButorType(DistributorChannelTypeCondition condition) {
        CustomerChannel customerChannel = getCustomerChannel(condition);
        customerChannel.setChannelStatus(customerChannel.getChannelStatus()==1?0:1);
        customerChannel.setUpdated(new Date());
        customerChannel.setUpdatedName(condition.getUpdatedByName());
        customerChannel.setUpdatedBy(condition.getUpdatedBy());
        return customerChannelMapper.updateByPrimaryKeySelective(customerChannel) > 0 ? true : false;
    }

    @Override
    public Boolean saveDistriButorChannel(DistributorChannelCondition channelCondition) {
        //校验分销商渠道名称是否重复
        validateDistriButorData(channelCondition);
        //如果渠道类型ID为空代表该操作为新增否则为修改
        CustomerChannel customerChannelByCondition = getCustomerChannelByCondition(channelCondition);
        Integer integer = saveOrUpdateChannelLevel(channelCondition, customerChannelByCondition);
        return integer == 0 ? false : true;
    }


    /**
     * 新增或修改分销商渠道级层次
     *
     * @param channelCondition
     * @param customerChannel
     */
    private Integer saveOrUpdateChannelLevel(DistributorChannelCondition channelCondition, CustomerChannel customerChannel) {
        List<CustomerDistributorLevel> distributorLevelList = channelCondition.getDistributorLevelList();
        int saveOrUpdate = 0;
        for (CustomerDistributorLevel distributorLevel : distributorLevelList) {
            Long channelLevelId = distributorLevel.getChannelLevelId();
            CustomerDistributorChannel distributorChannel = channelLevelId == null ? new CustomerDistributorChannel() :
                    customerDistributorChannelMapper.selectByPrimaryKey(distributorLevel.getChannelLevelId());
            distributorChannel.setStorePlanId(distributorLevel.getStorePlanId());
            distributorChannel.setLevelName(distributorLevel.getLevelName());
            distributorChannel.setLevel(distributorLevel.getLevel());
            distributorChannel.setStorePlanName(distributorLevel.getStorePlanName());
            if (null != channelLevelId) {
                distributorChannel.setUpdated(new Date());
                distributorChannel.setUpdatedBy(channelCondition.getUpdatedBy());
                distributorChannel.setUpdatedName(channelCondition.getUpdatedByName());
                saveOrUpdate = customerDistributorChannelMapper.updateByPrimaryKeySelective(distributorChannel);
            } else {
                distributorChannel.setChannelId(customerChannel.getId());
                distributorChannel.setCreated(new Date());
                distributorChannel.setCreatedBy(channelCondition.getCreatedBy());
                distributorChannel.setCreatedName(channelCondition.getCreatedByName());
                saveOrUpdate = customerDistributorChannelMapper.insertSelective(distributorChannel);
            }
            if (saveOrUpdate == 0) {
                logger.error("新增或修改分销商渠道级层级有误,操作失败--入参为--{}", JsonUtil.toJSONString(channelCondition));
                throw new BusinessException(BusinessCode.CODE_200019);
            }
        }
        return saveOrUpdate;
    }

    /**
     * 根据主键ID查询分销商渠道类型以及级层级信息
     *
     * @param id
     * @return
     */
    @Override
    public CustomerDistributorTypeAndChannelVO getDistributerChannelLevelById(Long id) {
        id = id == null ? 0L : id;
        CustomerChannel customerChannel = customerChannelMapper.selectByPrimaryKey(id);
        CustomerDistributorTypeAndChannelVO channelVO = new CustomerDistributorTypeAndChannelVO();
        if (null == customerChannel) {
            logger.error("回显分销商渠道类型级层级主键ID无效,操作失败--入参为--{}", JsonUtil.toJSONString(id));
            throw new BusinessException(BusinessCode.CODE_200008);
        }
        channelVO.setChannelId(customerChannel.getId());
        channelVO.setChannelName(customerChannel.getChannelName());
        channelVO.setPriceTypeId(customerChannel.getPriceTypeId());
        //通过渠道类型ID查询分销渠道级层级
        channelVO.setDistributorLevelList(customerDistributorChannelMapper.selectDistriButorLevelByChannelId(customerChannel.getId()));
        return channelVO;
    }

    /**
     * @param
     * @return
     * @author zhaoyanbiao
     * @date 2019年1月9日11:43:07
     * @Description 查询所有的分销商渠道类型列表
     */
    @Override
    public List<CustomerDistributorChannelTypeVO> findDistributerChannelTypeList(DistributorChannelTypeCondition condition) {
        return customerChannelMapper.findDistributerChannelTypeList(condition);
    }


    /**
     * zhaoyanbiao
     * 新增或者修改分销商渠道类型
     *
     * @param channelCondition
     */
    private CustomerChannel getCustomerChannelByCondition(DistributorChannelCondition channelCondition) {
        Long channelTypeId = channelCondition.getId();
        CustomerChannel customerChannel = channelTypeId == null ? new CustomerChannel() : customerChannelMapper.selectByPrimaryKey(channelTypeId);
        customerChannel.setChannelName(channelCondition.getChannelName());
        customerChannel.setPriceTypeId(channelCondition.getPriceTypeId());
        //是否存在默认的渠道如果有则之后的设置为非默认渠道
        channelCondition.setChannelSign(1);
        channelCondition.setChannelName("");
        Integer signFlag = customerChannelMapper.countDistriButorChannelByCondition(channelCondition);
        int saveOrUpdate = 0;
        if (null != channelTypeId) {
            customerChannel.setUpdated(new Date());
            customerChannel.setUpdatedBy(channelCondition.getUpdatedBy());
            customerChannel.setUpdatedName(channelCondition.getUpdatedByName());
            saveOrUpdate = customerChannelMapper.updateByPrimaryKeySelective(customerChannel);
        } else {
            customerChannel.setChannelSign(signFlag==0?1:0);
            customerChannel.setCreated(new Date());
            customerChannel.setCreatedBy(channelCondition.getCreatedBy());
            customerChannel.setCreatedName(channelCondition.getCreatedByName());
            customerChannel.setChannelStatus(CustomerUserLevelEnum.CUSTOMER_LEVEL_1.getCode());
            saveOrUpdate = customerChannelMapper.insertSelective(customerChannel);
        }
        if (saveOrUpdate == 0) {
            logger.error("新增或修改分销商渠道类型有误,操作失败--入参为--{}", JsonUtil.toJSONString(channelCondition));
            throw new BusinessException(BusinessCode.CODE_200017);
        }
        return customerChannel;
    }

    /**
     * 校验渠道的相关数据
     *
     * @param channelCondition
     */
    private void validateDistriButorData(DistributorChannelCondition channelCondition) {
        //校验渠道名称是否重复
        Integer countChannelByName = customerChannelMapper.countDistriButorChannelByCondition(channelCondition);
        if(channelCondition.getId() == null)
        {
            if (countChannelByName >= CustomerUserLevelEnum.CUSTOMER_LEVEL_1.getCode()) {
                logger.error("新增分销商渠道名称重复,操作失败--入参为--{}", JsonUtil.toJSONString(channelCondition));
                throw new BusinessException(BusinessCode.CODE_200015);
            }
        }else {
            CustomerChannel customerChannel = customerChannelMapper.selectByPrimaryKey(channelCondition.getId());
            if(!customerChannel.getChannelName().equals(channelCondition.getChannelName()))
            {
                if (countChannelByName >= CustomerUserLevelEnum.CUSTOMER_LEVEL_1.getCode()) {
                    logger.error("修改分销商渠道名称重复,操作失败--入参为--{}", JsonUtil.toJSONString(channelCondition));
                    throw new BusinessException(BusinessCode.CODE_200015);
                }
            }

        }

        //校验渠道等级必须为三个层次

        List<CustomerDistributorLevel> distributorLevelList = channelCondition.getDistributorLevelList();
        if (distributorLevelList.size() != CustomerUserLevelEnum.CUSTOMER_LEVEL_3.getCode()) {
            logger.error("新增或修改分销商渠道级层次有误,操作失败--入参为--{}", JsonUtil.toJSONString(channelCondition));
            throw new BusinessException(BusinessCode.CODE_200016);
        }
    }

    /**
     * 校验更新分销商渠道类型condition如果没有问题将返回分销商渠道类型对象
     *
     * @param condition
     * @return
     */
    private CustomerChannel getCustomerChannel(DistributorChannelTypeCondition condition) {
        if (null == condition.getId()) {
            logger.error("分销商修改渠道类型修改的对象主键ID为空--条件为--{}", JsonUtil.toJSONString(condition));
            throw new BusinessException(BusinessCode.CODE_200006);
        }
        if (null == condition.getChannelStatus()) {
            logger.error("分销商修改渠道类型修改状态值为空--条件为--{}", JsonUtil.toJSONString(condition));
            throw new BusinessException(BusinessCode.CODE_200007);
        } else if (condition.getChannelStatus() != 1 && condition.getChannelStatus() != 0) {
            logger.error("分销商修改渠道类型修改状态值无效--条件为--{}", JsonUtil.toJSONString(condition));
            throw new BusinessException(BusinessCode.CODE_200007);
        }
        CustomerChannel customerChannel = customerChannelMapper.selectByPrimaryKey(condition.getId());
        if (null == customerChannel) {
            logger.error("分销商修改渠道类型对象不存在主键ID无效--条件为--{}", JsonUtil.toJSONString(condition));
            throw new BusinessException(BusinessCode.CODE_200008);
        }
        return customerChannel;
    }

}
